import { ref } from 'vue'

// 默认返回格式
const defaultCallBack = (res = {}) => {
  if (!res) return {}
  const { errno, data, errmsg } = res || {}
  return {
    errno,
    data,
    errmsg
  }
}

export default ({
  request,
  params = {},
  init = true,
  calback = defaultCallBack,
  onSuccess = null,
  onError = null
}) => {
  const loading = ref(false)
  const result = ref(null)

  const doResult = async (params) => {
    try {
      loading.value = true
      const res = await request(params)
      const data = calback ? calback(res) : res
      loading.value = false
      if (data?.errno === 0) {
        result.value = data?.data || null
        onSuccess && onSuccess(data)
      } else {
        result.value = null
        onError && onError(data)
      }
      return res
    } catch (error) {
      request.value = null
      loading.value = false
      onError && onError(error)
    }
    loading.value = false
  }

  init && doResult(params)

  return {
    loading,
    result,
    doResult
  }
}
